<template>
  <el-dialog
    v-model="visible"
    width="700px"
    :close-on-click-modal="false"
    :show-close="canClose"
    append-to-body
    class="unified-dialog batch-dialog-progress"
  >
    <template #header>
      <div class="dialog-header">
        <div class="header-icon" :class="headerIconClass">
          <el-icon v-if="!isCompleted"><Loading /></el-icon>
          <el-icon v-else-if="hasErrors"><Warning /></el-icon>
          <el-icon v-else><CircleCheck /></el-icon>
        </div>
        <div class="header-content">
          <h3>{{ title }}</h3>
          <p>{{ subtitle }}</p>
        </div>
      </div>
    </template>

    <div class="progress-container">
      <!-- 操作提示 -->
      <el-alert
        v-if="!isCompleted"
        type="info"
        :closable="false"
        show-icon
        class="operation-tip"
      >
        <template #title>
          <span style="font-size: 13px;">💡 提示：请勿关闭此对话框，可点击下方"后台运行"按钮继续其他操作</span>
        </template>
      </el-alert>
      
      <!-- 总体进度 -->
      <div class="overall-progress">
        <div class="progress-stats">
          <span class="stat-item">
            <span class="stat-label">总计:</span>
            <span class="stat-value">{{ totalJobs }}</span>
          </span>
          <span class="stat-item success">
            <span class="stat-label">成功:</span>
            <span class="stat-value">{{ successCount }}</span>
          </span>
          <span class="stat-item error">
            <span class="stat-label">失败:</span>
            <span class="stat-value">{{ failureCount }}</span>
          </span>
          <span class="stat-item">
            <span class="stat-label">剩余:</span>
            <span class="stat-value">{{ remainingCount }}</span>
          </span>
        </div>
        <el-progress
          :percentage="progressPercentage"
          :status="progressStatus"
          :stroke-width="20"
        />
      </div>

      <!-- 当前处理的作业 -->
      <div v-if="currentJob" class="current-job">
        <el-card shadow="never">
          <div class="current-job-header">
            <el-icon class="rotating"><Loading /></el-icon>
            <span>正在处理</span>
          </div>
          <div class="current-job-name">{{ currentJob }}</div>
        </el-card>
      </div>

      <!-- 任务列表 -->
      <div class="jobs-list">
        <el-scrollbar max-height="300px">
          <div
            v-for="(job, index) in jobResults"
            :key="index"
            class="job-item"
            :class="job.status"
          >
            <div class="job-item-content">
              <el-icon v-if="job.status === 'pending'" class="job-icon"><Clock /></el-icon>
              <el-icon v-else-if="job.status === 'processing'" class="job-icon rotating"><Loading /></el-icon>
              <el-icon v-else-if="job.status === 'success'" class="job-icon"><CircleCheck /></el-icon>
              <el-icon v-else-if="job.status === 'error'" class="job-icon"><CircleClose /></el-icon>
              
              <span class="job-name">{{ job.name }}</span>
              
              <el-tag
                v-if="job.status === 'success'"
                type="success"
                size="small"
                effect="light"
              >
                成功
              </el-tag>
              <el-tag
                v-else-if="job.status === 'error'"
                type="danger"
                size="small"
                effect="light"
              >
                失败
              </el-tag>
              <el-tag
                v-else-if="job.status === 'processing'"
                type="warning"
                size="small"
                effect="light"
              >
                处理中
              </el-tag>
              <el-tag
                v-else
                type="info"
                size="small"
                effect="light"
              >
                等待中
              </el-tag>
            </div>
            <div v-if="job.error" class="job-error">
              {{ job.error }}
            </div>
          </div>
        </el-scrollbar>
      </div>
    </div>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button 
          v-if="!isCompleted" 
          @click="runInBackground"
          plain
        >
          后台运行
        </el-button>
        <el-button 
          v-if="isCompleted"
          @click="handleClose"
          :type="hasErrors ? 'warning' : 'success'"
        >
          关闭
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, computed, watch, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Loading, Warning, CircleCheck, CircleClose, Clock } from '@element-plus/icons-vue'

const props = defineProps({
  modelValue: {
    type: Boolean,
    default: false
  },
  jobs: {
    type: Array,
    default: () => []
  }
})

const emit = defineEmits(['update:modelValue', 'background', 'complete'])

// 如果没有传入jobs，使用默认演示数据
const defaultJobs = [
  { name: 'ods_xhs_note_list_keyword' },
  { name: 'ods_user_behavior_log' },
  { name: 'ods_order_info' },
  { name: 'ods_product_info' },
  { name: 'ods_payment_record' }
]

const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

const totalJobs = computed(() => {
  const jobsToProcess = props.jobs.length > 0 ? props.jobs : defaultJobs
  return jobsToProcess.length
})
const currentJob = ref('')
const jobResults = ref([])
const runInBackgroundFlag = ref(false)

const successCount = computed(() => jobResults.value.filter(j => j.status === 'success').length)
const failureCount = computed(() => jobResults.value.filter(j => j.status === 'error').length)
const remainingCount = computed(() => jobResults.value.filter(j => j.status === 'pending' || j.status === 'processing').length)

const progressPercentage = computed(() => {
  if (totalJobs.value === 0) return 0
  return Math.round((successCount.value + failureCount.value) / totalJobs.value * 100)
})

const progressStatus = computed(() => {
  if (hasErrors.value) return 'exception'
  if (isCompleted.value) return 'success'
  return null
})

const isCompleted = computed(() => {
  return jobResults.value.length > 0 && 
         jobResults.value.every(j => j.status === 'success' || j.status === 'error')
})

const hasErrors = computed(() => failureCount.value > 0)

const canClose = computed(() => isCompleted.value || runInBackgroundFlag.value)

const title = computed(() => {
  if (isCompleted.value) {
    return hasErrors.value ? '批量操作完成（部分失败）' : '批量操作完成'
  }
  return '批量操作进行中'
})

const subtitle = computed(() => {
  if (isCompleted.value) {
    return `成功: ${successCount.value}, 失败: ${failureCount.value}`
  }
  return `正在处理 ${remainingCount.value} 个任务...`
})

const headerIconClass = computed(() => {
  if (!isCompleted.value) return 'header-icon-primary'
  if (hasErrors.value) return 'header-icon-warning'
  return 'header-icon-success'
})

// 模拟批量操作执行
const executeBatchOperation = async () => {
  // 如果没有传入jobs，使用默认演示数据
  const jobsToProcess = props.jobs.length > 0 
    ? props.jobs 
    : defaultJobs
  
  // 初始化任务列表
  jobResults.value = jobsToProcess.map(job => ({
    name: job.name || job.topic_name || job.job_name,
    status: 'pending',
    error: null
  }))
  
  // 逐个处理任务
  for (let i = 0; i < jobResults.value.length; i++) {
    const job = jobResults.value[i]
    job.status = 'processing'
    currentJob.value = job.name
    
    // 模拟处理时间（随机1-3秒）
    await new Promise(resolve => setTimeout(resolve, Math.random() * 2000 + 1000))
    
    // 随机成功/失败（90%成功率）
    if (Math.random() > 0.1) {
      job.status = 'success'
    } else {
      job.status = 'error'
      job.error = '模拟错误：操作超时'
    }
    
    currentJob.value = ''
  }
  
  emit('complete', {
    success: successCount.value,
    failure: failureCount.value
  })
}

const handleClose = () => {
  visible.value = false
  // 重置状态
  jobResults.value = []
  currentJob.value = ''
  runInBackgroundFlag.value = false
}

const runInBackground = () => {
  runInBackgroundFlag.value = true
  emit('background', {
    current: successCount.value + failureCount.value,
    total: totalJobs.value,
    successCount: successCount.value,
    failureCount: failureCount.value
  })
  ElMessage.info('任务将在后台继续执行')
}

// 监听对话框显示，开始执行
watch(visible, (newVal) => {
  if (newVal && jobResults.value.length === 0) {
    executeBatchOperation()
  }
})

onMounted(() => {
  if (visible.value) {
    executeBatchOperation()
  }
})
</script>

<style scoped>
.operation-tip {
  margin-bottom: 20px;
}

.progress-container {
  padding: 0;
}

.overall-progress {
  margin-bottom: 24px;
}

.progress-stats {
  display: flex;
  justify-content: space-around;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 8px;
}

.stat-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.stat-item.success .stat-label,
.stat-item.success .stat-value {
  color: #67c23a;
}

.stat-item.error .stat-label,
.stat-item.error .stat-value {
  color: #f56c6c;
}

.stat-label {
  font-size: 12px;
  color: #909399;
}

.stat-value {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
}

.current-job {
  margin-bottom: 20px;
}

.current-job-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  color: #409eff;
  font-weight: 500;
}

.current-job-header .rotating {
  animation: rotate 1s linear infinite;
}

.current-job-name {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.jobs-list {
  margin-top: 20px;
}

.job-item {
  padding: 12px;
  margin-bottom: 8px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
  transition: all 0.3s ease;
}

.job-item:hover {
  background: #f0f2f5;
  border-color: #c0c4cc;
}

.job-item.success {
  background: #f0f9ff;
  border-color: #67c23a;
}

.job-item.error {
  background: #fef0f0;
  border-color: #f56c6c;
}

.job-item.processing {
  background: #fdf6ec;
  border-color: #e6a23c;
}

.job-item-content {
  display: flex;
  align-items: center;
  gap: 12px;
}

.job-icon {
  font-size: 18px;
}

.job-icon.rotating {
  animation: rotate 1s linear infinite;
}

.job-name {
  flex: 1;
  font-size: 14px;
  font-weight: 500;
  color: #303133;
}

.job-error {
  margin-top: 8px;
  padding: 8px;
  background: white;
  border-radius: 4px;
  font-size: 12px;
  color: #f56c6c;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>

